package com.southminority.ethnic.controller.admin.heritage;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.Heritage;
import com.southminority.ethnic.pojo.Inheritor;
import com.southminority.ethnic.service.heritage.HeritageService;
import com.southminority.ethnic.controller.heritage.vo.HeritageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 非遗项目管理后台控制器
 * 提供管理员的完整CRUD操作
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "07 - 非物质文化遗产管理API", description = "【后台】非物质文化遗产、传承人等模块的增删改查接口")
@RestController
@RequestMapping("/admin/heritage")
@CrossOrigin
public class HeritageAdminController {

    private final HeritageService heritageService;

    public HeritageAdminController(HeritageService heritageService) {
        this.heritageService = heritageService;
    }

    /**
     * 分页查询非遗项目列表
     */
    @GetMapping("/page")
    @Operation(summary = "【非遗项目】分页和条件查询", description = "后台管理使用的非遗项目列表接口，支持多种条件筛选和分页。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<PageResult<HeritageVO>> getHeritagePageForAdmin(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "搜索关键词，模糊匹配名称、简介等", example = "苗族") @RequestParam(required = false) String keyword,
            @Parameter(description = "非遗类型", example = "传统技艺") @RequestParam(required = false) String heritageType,
            @Parameter(description = "级别", example = "省级") @RequestParam(required = false) String level,
            @Parameter(description = "状态", example = "1", schema = @Schema(description = "1-已发布, 0-草稿, -1-已删除", type = "integer", allowableValues = {"1", "0", "-1"})) @RequestParam(required = false) Integer status) {
        try {
            PageResult<HeritageVO> pageResult = heritageService.getHeritagePageForAdmin(
                page, size, keyword, heritageType, level, status);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("分页查询非遗项目失败", e);
            return R.fail("分页查询非遗项目失败: " + e.getMessage());
        }
    }

    /**
     * 创建非遗项目
     */
    @PostMapping("/create")
    @Operation(summary = "【非遗项目】新增一个非遗项目", description = "传入非遗项目的完整信息（除ID外）来创建一个新的项目记录。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功，返回创建后的项目信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<HeritageVO> createHeritage(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "非遗项目信息的JSON对象", required = true,
            content = @Content(schema = @Schema(implementation = Heritage.class)))
            @org.springframework.web.bind.annotation.RequestBody com.southminority.ethnic.pojo.Heritage heritage) {
        try {
            log.info("管理员创建非遗项目: {}", heritage.getTitle());
            HeritageVO result = heritageService.createHeritage(heritage);
            return R.ok(result);
        } catch (Exception e) {
            log.error("创建非遗项目失败", e);
            return R.fail("创建非遗项目失败: " + e.getMessage());
        }
    }

    /**
     * 更新非遗项目
     */
    @PutMapping("/update/{id}")
    @Operation(summary = "【非遗项目】根据ID更新项目信息", description = "提供非遗项目的ID和更新后的信息，对现有记录进行修改。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功，返回更新后的项目信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "404", description = "非遗项目不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<HeritageVO> updateHeritage(
            @Parameter(description = "要更新的非遗项目ID", example = "1", required = true) @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "包含更新字段的非遗项目JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = Heritage.class)))
            @org.springframework.web.bind.annotation.RequestBody com.southminority.ethnic.pojo.Heritage heritage) {
        try {
            log.info("管理员更新非遗项目: ID={}", id);
            HeritageVO result = heritageService.updateHeritage(id, heritage);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新非遗项目失败", e);
            return R.fail("更新非遗项目失败: " + e.getMessage());
        }
    }

    /**
     * 删除非遗项目
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "【非遗项目】根据ID逻辑删除项目", description = "将指定ID的非遗项目状态设置为-1（已删除），并非物理删除。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "非遗项目不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> deleteHeritage(@Parameter(description = "要删除的非遗项目ID", example = "1", required = true) @PathVariable Long id) {
        try {
            log.info("管理员删除非遗项目: ID={}", id);
            Boolean result = heritageService.deleteHeritage(id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("删除非遗项目失败", e);
            return R.fail("删除非遗项目失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除非遗项目
     */
    @DeleteMapping("/batch-delete")
    @Operation(summary = "【非遗项目】批量逻辑删除", description = "传入一个ID列表，批量将对应的非遗项目状态设置为-1。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "批量删除成功"),
            @ApiResponse(responseCode = "400", description = "ID列表为空"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> batchDeleteHeritage(@RequestBody(description = "包含多个非遗项目ID的数组", required = true,
            content = @Content(schema = @Schema(type = "array", implementation = Long.class))) List<Long> ids) {
        try {
            log.info("管理员批量删除非遗项目: IDs={}", ids);
            Boolean result = heritageService.batchDeleteHeritage(ids);
            return R.ok(result);
        } catch (Exception e) {
            log.error("批量删除非遗项目失败", e);
            return R.fail("批量删除非遗项目失败: " + e.getMessage());
        }
    }

    /**
     * 更新非遗项目状态
     */
    @PutMapping("/status/{id}")
    @Operation(summary = "【非遗项目】更新状态", description = "更新单个非遗项目的状态，如发布（1）和草稿（0）。")
    @Parameters({
            @Parameter(name = "id", description = "非遗项目ID", example = "1", required = true),
            @Parameter(name = "status", description = "新的状态值", example = "0", required = true,
                    schema = @Schema(description = "1-已发布, 0-草稿", type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "状态更新成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "非遗项目不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> updateHeritageStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        try {
            log.info("管理员更新非遗项目状态: ID={}, Status={}", id, status);
            Boolean result = heritageService.updateHeritageStatus(id, status);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新非遗项目状态失败", e);
            return R.fail("更新非遗项目状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取非遗项目详情（管理端）
     */
    @GetMapping("/detail/{id}")
    @Operation(summary = "【非遗项目】获取后台编辑详情", description = "获取单个非遗项目的完整信息，用于后台管理界面的编辑表单。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "非遗项目不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<HeritageVO> getHeritageDetailForAdmin(@Parameter(description = "非遗项目ID", example = "1", required = true) @PathVariable Long id) {
        try {
            HeritageVO result = heritageService.getHeritageDetailForAdmin(id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("获取非遗项目详情失败, ID: {}", id, e);
            return R.fail("获取非遗项目详情失败: " + e.getMessage());
        }
    }

    // ====================================
    // 传承人管理接口
    // ====================================

    /**
     * 创建传承人
     */
    @PostMapping("/inheritor/create")
    @Operation(summary = "【传承人】新增一个传承人", description = "为某个非遗项目关联并创建一个新的传承人。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> createInheritor(@RequestBody(description = "传承人信息的JSON对象", required = true,
            content = @Content(schema = @Schema(implementation = Inheritor.class))) Inheritor inheritor) {
        try {
            log.info("管理员创建传承人: {}", inheritor.getName());
            Boolean result = heritageService.createInheritor(inheritor);
            return R.ok(result);
        } catch (Exception e) {
            log.error("创建传承人失败", e);
            return R.fail("创建传承人失败: " + e.getMessage());
        }
    }

    /**
     * 更新传承人
     */
    @PutMapping("/inheritor/update/{id}")
    @Operation(summary = "【传承人】根据ID更新传承人信息", description = "提供传承人的ID和更新后的信息，对现有记录进行修改。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "404", description = "传承人不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> updateInheritor(
            @Parameter(description = "要更新的传承人ID", example = "1", required = true) @PathVariable Long id,
            @RequestBody(description = "包含更新字段的传承人JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = Inheritor.class))) Inheritor inheritor) {
        try {
            log.info("管理员更新传承人: ID={}", id);
            Boolean result = heritageService.updateInheritor(id, inheritor);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新传承人失败", e);
            return R.fail("更新传承人失败: " + e.getMessage());
        }
    }

    /**
     * 删除传承人
     */
    @DeleteMapping("/inheritor/delete/{id}")
    @Operation(summary = "【传承人】根据ID逻辑删除传承人", description = "将指定ID的传承人状态设置为-1，并非物理删除。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "传承人不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> deleteInheritor(@Parameter(description = "要删除的传承人ID", example = "1", required = true) @PathVariable Long id) {
        try {
            log.info("管理员删除传承人: ID={}", id);
            Boolean result = heritageService.deleteInheritor(id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("删除传承人失败", e);
            return R.fail("删除传承人失败: " + e.getMessage());
        }
    }

    /**
     * 根据非遗项目ID获取传承人列表
     */
    @GetMapping("/inheritor/list/{heritageId}")
    @Operation(summary = "【传承人】获取指定非遗项目下的所有传承人", description = "根据非遗项目ID，查询其关联的所有传承人列表（不分页）。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<List<Inheritor>> getInheritorsByHeritageId(
            @Parameter(description = "非遗项目的ID", example = "1", required = true) @PathVariable Long heritageId) {
        try {
            List<Inheritor> result = heritageService.getInheritorsByHeritageId(heritageId);
            return R.ok(result);
        } catch (Exception e) {
            log.error("获取传承人列表失败, HeritageId: {}", heritageId, e);
            return R.fail("获取传承人列表失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询传承人（后台管理）：默认返回全部，可按 heritageId/keyword/status 过滤。
     */
    @GetMapping("/inheritor/page")
    @Operation(summary = "【传承人】分页和条件查询", description = "后台管理传承人列表，支持按所属非遗/关键词/状态筛选")
    public R<com.southminority.ethnic.common.result.PageResult<Inheritor>> getInheritorPage(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "所属非遗项目ID", example = "1") @RequestParam(required = false) Long heritageId,
            @Parameter(description = "关键词(姓名/民族/级别/专长)") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态(1正常,0禁用,-1删除)") @RequestParam(required = false) Integer status
    ) {
        try {
            log.info("[ADMIN] GET /admin/heritage/inheritor/page -> page={}, size={}, heritageId={}, keyword={}, status={}",
                    page, size, heritageId, keyword, status);
            var result = heritageService.getInheritorPageForAdmin(page, size, heritageId, keyword, status);
            log.info("[ADMIN] Inheritor page result: total={}, size={}, current={}",
                    result.getTotal(), result.getSize(), result.getCurrent());
            return R.ok(result);
        } catch (Exception e) {
            log.error("分页查询传承人失败", e);
            return R.fail("分页查询传承人失败: " + e.getMessage());
        }
    }

    /**
     * 测试管理端接口连通性
     */
    @GetMapping("/test")
    @Operation(summary = "测试管理端接口连通性", description = "一个简单的GET请求，用于检查服务是否正常运行。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "服务正常")
    })
    public R<String> test() {
        return R.ok("非遗项目管理端服务正常运行");
    }
} 